<template>
  <!-- 用户信息 -->
  <div class="userInfo_avatar">
    <!-- 展示信息区域 -->
    <div class="userInfo_avatar_box">
      <!-- 用户背景区域 -->
      <el-card class="box-card-pic" v-loading="loadingAnimation.pic_bg">
        <div class="userInfo_pic_box">
          <img :src="aimUserInfo.pic_bg" class="img-fluid w-100 h-100" alt="" />
        </div>
        <div class="gengxin" v-if="aimUserInfo.id === userInfo.id">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            action=""
            ref="upload2"
            :before-upload="beforeAvatarUpload2"
          >
            <button><i class="iconfont icon-photo"></i>上传封面图片</button>
          </el-upload>
        </div>
      </el-card>
      <!-- 用户头像 -->
      <div class="avatar">
        <img
          v-lazy="aimUserInfo.profile"
          alt=""
          class="img-fluid w-100 h-100"
        />
        <el-upload
          v-if="aimUserInfo.id === userInfo.id"
          class="avatar-uploader"
          :show-file-list="false"
          action=""
          ref="upload"
          v-loading="loadingAnimation.avatar"
          :before-upload="beforeAvatarUpload"
        >
          <div class="updateAvatar">
            <i class="iconfont icon-photo"></i><br />更新我的头像
          </div>
        </el-upload>
      </div>
      <!-- 用户头像区域 -->
      <el-card class="box-card">
        <div class="userInfo_base">
          <p class="nickName">{{ aimUserInfo.nickName | uncodeUtf16 }}</p>
          <p
            class="description"
            :style="aimUserInfo.id === userInfo.id ? '' : 'max-width: 824px;'"
          >
            {{ handlerEmoji | uncodeUtf16 }}
          </p>
        </div>
        <!-- 关注私信 -->
        <div class="concernBox">
          <div
            class="concern"
            :class="concern ? 'active' : ''"
            @click="myConcern"
          >
            <i
              class="el-icon-plus"
              :style="concern ? 'display:none;' : 'display:inline-block;'"
            ></i>
            <span>{{ concern ? "取消关注" : " 关注Ta" }}</span>
          </div>
          <div class="private">
            <span>发私信</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>
 
<script>
import { mapState, mapActions } from "vuex";
import { updateProfile, updatePicBg } from "@/api/users";
import { transformUserInfoTime } from "@/utils/format_date";
import { throttle } from "lodash";
import dayjs from "dayjs";
import axios from "axios";
import $ from "jquery";

export default {
  name: "MyAvatar",
  computed: {
    ...mapState("user", ["aimUserInfo", "userInfo"]),
    handlerEmoji() {
      if (this.aimUserInfo.description) {
        return this.aimUserInfo.description;
      } else {
        return `本站第 ${
          this.aimUserInfo.id
        } 位用户，入住本站${transformUserInfoTime(
          this.aimUserInfo.createTime
        )}`;
      }
    },
  },
  watch: {
    // 控制关注和私信的显示隐藏
    aimUserInfo() {
      if (this.aimUserInfo.id === this.userInfo.id) {
        $(".concernBox").hide();
      } else {
        $(".concernBox").show();
        if (this.userInfo.concern) {
          const jsonCollect = JSON.parse(this.userInfo.concern).content.find(
            (item) => {
              if (item === this.aimUserInfo.user_id) return true;
            }
          );
          jsonCollect === undefined
            ? (this.concern = false)
            : (this.concern = true);
        }
      }
    },
  },
  data() {
    return {
      // 控制显示加载动画
      loadingAnimation: {
        pic_bg: false, // 封面图片上传加载
        avatar: false, // 头像图片上传加载
        skeleton: true, // 骨架屏显示
      },
      // GitHub 配置参数
      github: {
        // https://api.github.com/repos/用户名/仓库名/contents/文件路径
        Folder: "img", // 存放文件夹
        url: "https://api.github.com/repos", // api接口地址
        token: "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", // github 授权令牌
        owner: "ChaiMayor", // github 用户名
        repo: "markImages", // 图库名
      },
      concern: false,
    };
  },
  methods: {
    ...mapActions("user", { updateUserInfo: "updateUserInfo" }),
    // 关注点击事件
    myConcern: throttle(function () {
      this.$parent
        .toolRequest(
          "guan",
          this.concern ? 1 : 0,
          this.aimUserInfo.user_id,
          this.userInfo.user_id
        )
        .then(() => {
          this.concern = !this.concern;
        });
    }, 4000),
    // 用户上传头像之前触发的回调
    beforeAvatarUpload(file) {
      // 判断文件大小
      let status = file.size / 1024 / 1024 < 1;
      if (!status) {
        this.uploadavatar_flag = true;
        return this.$message({
          message: "图片大小不能超过 1 MB",
          type: "error",
          duration: 5 * 1000,
        });
      }
      // 创建文件对象
      let fileReader = new FileReader();
      // 将文件转换为base64位格式编码
      fileReader.readAsDataURL(file);
      // 转换完毕后调用
      fileReader.onload = () => {
        /* 解析完成结果 */
        let result = fileReader.result;
        this.uploadPicbg(file, result, 0);
      };
    },
    // 用户上传封面之前触发的回调
    beforeAvatarUpload2(file) {
      // 判断文件大小
      let status = file.size / 1024 / 1024 < 1;
      if (!status) {
        this.uploadavatar_flag = true;
        return this.$message({
          message: "图片大小不能超过 1 MB",
          type: "error",
          duration: 5 * 1000,
        });
      }
      // 创建文件对象
      let fileReader = new FileReader();
      // 将文件转换为base64位格式编码
      fileReader.readAsDataURL(file);
      // 转换完毕后调用
      fileReader.onload = () => {
        /* 解析完成结果 */
        let result = fileReader.result;
        this.uploadPicbg(file, result, 1);
      };
    },
    // 文章上传封面图片
    uploadPicbg($file, pic, flag) {
      // 判断是头像还是封面
      /**
       * 0 头像
       * 1 封面
       */
      if (flag === 0) {
        this.loadingAnimation.avatar = true;
        // 取消默认的上传文件请求，改为手动发送
        this.$refs.upload.abort();
      } else {
        this.loadingAnimation.pic_bg = true;
        // 取消默认的上传文件请求，改为手动发送
        this.$refs.upload2.abort();
      }
      // 配置路径接口
      const filename = `${+dayjs()}.${$file["name"].split(".")[1]}`;
      const filepath = `${this.github.Folder}/${filename}`;
      // 拼接目标路径
      const target = `${this.github.url}/${this.github.owner}/${this.github.repo}/contents/${filepath}`;

      // 文件的base64编码
      const base64 = pic.substring(pic.indexOf(",") + 1); // 取得逗号后面的数据

      // body 参数
      var predata = {
        message: "commit from images",
        content: base64,
        branch: "main",
      };

      axios({
        url: target,
        method: "PUT",
        data: JSON.stringify(predata),
        headers: {
          "Content-Type": "application/vnd.github+json",
          Authorization: `Bearer ${this.github.token}`,
        },
      }).then(async (options) => {
        const url = `https://cdn.jsdelivr.net/gh/${this.github.owner}/${this.github.repo}/${options.data.content.path}`;
        let result = null;
        if (flag === 0) {
          result = await updateProfile({
            user_id: this.aimUserInfo.user_id,
            profile: url,
          });
        } else {
          result = await updatePicBg({
            user_id: this.aimUserInfo.user_id,
            pic_bg: url,
          });
        }
        if (result.code === 200) {
          this.$message({
            message: `${flag ? "封面上传" : "头像更改"}成功`,
            type: "success",
            duration: 5 * 1000,
          });
          // 更新全局用户信息
          this.updateUserInfo();
          if (flag === 0) {
            this.loadingAnimation.avatar = false;
          } else {
            this.loadingAnimation.pic_bg = false;
          }
        } else {
          this.loadingAnimation.avatar = false;
          this.loadingAnimation.pic_bg = false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.userInfo_avatar {
  display: flex;
  flex-direction: column;
  background: #fff;
  max-width: 1200px;
  position: relative;
  margin: 0 auto;
  .concernBox {
    position: absolute;
    z-index: 2;
    right: 20px;
    top: 40px;
    display: flex;
    user-select: none;
    & > div {
      transition: transform 0.4s;
      cursor: url("@/assets/mouse/x2.cur"), auto !important;
      &:active {
        transform: translateY(1px);
      }
    }
    .concern {
      background: #0dce9e;
      border: 1px solid #0dce9e;
      border-radius: 6px;
      color: #fff;
      padding: 8px 16px;
      transition: opacity 0.2s;
      white-space: nowrap;
      font-size: 12px;
      &.active {
        opacity: 0.5;
      }
      i {
        font-weight: 700;
      }
    }
    .private {
      opacity: 0.9;
      transition: opacity 0.2s;
      margin-left: 10px;
      color: #0dce9e;
      font-size: 12px;
      white-space: nowrap;
      border: 1px solid #0dce9e;
      border-radius: 6px;
      padding: 8px 16px;
      background: rgba(255, 255, 255, 0);
    }
  }
  .description {
    max-width: 1016px;
    height: 48px;
    /* 省略号 */
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .userInfo_pic_box {
    width: 100%;
    max-height: 240px;
  }
  .box-card-pic {
    border-radius: 0;
    position: relative;
    .gengxin {
      position: absolute;
      right: 10px;
      top: 10px;
      button {
        outline: none;
        background: none;
        color: #fff;
        border: 1px solid #fff;
        font-size: 13px;
        border-radius: 4px;
        padding: 2px 12px;
      }
      .icon-photo {
        margin-right: 4px;
        font-size: 14px;
        vertical-align: middle;
      }
    }
  }
  .avatar {
    overflow: hidden;
    width: 120px;
    height: 120px;
    border: 4px solid #fff;
    box-shadow: 0 0 10px 2px rgb(0 0 0 / 7%);
    position: absolute;
    left: 30px;
    border-radius: 50%;
    bottom: 28px;
    z-index: 2002;
    &:hover {
      /deep/ .avatar-uploader {
        .updateAvatar {
          display: block;
        }
      }
    }
    /deep/ .avatar-uploader {
      width: 100%;
      height: 100%;
      position: absolute;
      z-index: 2;
      left: 0;
      top: 0;
      .icon-photo {
        font-size: 18px;
      }
      .el-upload {
        width: 100%;
        height: 100%;
      }
      .updateAvatar {
        background: rgba(41, 44, 47, 0.4);
        display: none;
        padding-top: 30px;
        width: 100%;
        height: 100%;
        font-size: 13px;
        color: #fff;
      }
    }
  }
  .userInfo_base {
    margin-left: 172px;
    padding-top: 4px;
    text-align: left;
    .nickName {
      color: #222226;
      font-weight: 500;
      line-height: 24px;
      font-size: 20px;
    }
    .updateAvatar {
      border: 1px solid #ccc;
      color: #ccc;
      background: #fff;
      padding: 2px 8px;
      border-radius: 4px;
      font-size: 14px;
      transition: color 0.6s, border 0.6s;
      &:hover {
        border: 1px solid #222;
        color: #222;
      }
    }
  }
  .box-card {
    padding-bottom: 12px;
    padding-top: 12px;
    position: relative;
  }
  /deep/ .el-card {
    box-shadow: none;
    border: none;
    width: 100%;
    .el-card__body {
      padding: 0;
      display: flex;
    }
  }
}
</style>